//
//  NetWorkingManager.m
//  Clinic_Doctor
//
//  Created by 杨春至 on 2017/4/10.
//  Copyright © 2017年 提运佳. All rights reserved.
//

#import "NetWorkingManager.h"
#import "ZZBaseViewController.h"

static NSString *const HOST_URL = TestRequestHeader;

typedef void(^NWreachableblock)(void);
NWreachableblock NWblock;
static  BOOL isDisToConnected;
@implementation NetWorkingManager
+ (NetWorkingManager *)sharedNetManager{
    static NetWorkingManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetWorkingManager alloc]init];
    });
    return manager;
}

+(void)getWithRequestUrl:(NSString *)requestHead AndParameters:(NSDictionary *)param AndRequestBlock:(void(^)(NSDictionary *responseObject))block FailBlock:(void(^)(NSDictionary *errDic))failBlock{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSString *UrlStr;
    if ([requestHead hasPrefix:@"http"]) {
        UrlStr = [requestHead copy];
    }else{
        UrlStr = [NSString stringWithFormat:@"%@%@",HOST_URL,requestHead];
    }
     NSLog(@"请求头%@ \n 参数%@",UrlStr,param);
    [manager GET:UrlStr parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          NSLog(@"返回参数%@",responseObject);
             block(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(@{@"errorMsg":@"网络异常"});
          NSLog(@"%@",error);
    }];
    
}

+(void)
postWithRequestUrl:(NSString *)requestHead AndParameters:(NSDictionary *)param AndRequestBlock:(void(^)(NSDictionary *responseObject))block FailBlock:(void(^)(NSDictionary *errDic))failBlock ShowTips:(BOOL)showTips{
    
//    [netManager reachNetwork];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *UrlStr;
    if ([requestHead hasPrefix:@"http"]) {
        UrlStr = requestHead;
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        UrlStr = [NSString stringWithFormat:@"%@%@",HOST_URL,requestHead];
    }

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];

    
    NSLog(@"请求头%@ \n 参数%@",UrlStr,param);
    ZZBaseViewController  *baseVC  = (id)[ZZHelper topViewController];
    QMUITips *tips = [QMUITips showLoadingInView:baseVC.view];
    [manager POST:UrlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *respondDict = responseObject;
        [tips hideAnimated:YES];
        if ([respondDict.allKeys containsObject:@"end"]) {
            if (![respondDict[@"end"] isEqualToString:@"ok"]) {
                if ([respondDict[@"end"] isEqualToString:@"noLogin"]) {
                 
//                    在非个人页面 当需要登录时进行登录操作
                    if(![baseVC isKindOfClass:NSClassFromString(@"MeVC")]&&![baseVC isKindOfClass:NSClassFromString(@"ZZLCLoginVC")])
                    {
                        [baseVC jumpToLogVC];
                        [QMUITips showError:responseObject[@"message"] inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:1.8];
                    }
                }else{
                    if (showTips) {
                        [QMUITips showError:responseObject[@"message"] inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:1.8];
                    }
                }
                if (failBlock) {
                        failBlock(@{@"sate":responseObject[@"end"],@"errorMsg":responseObject[@"message"]});
                }
            }else{
       
                  block(responseObject);
            }
        }else{
              block(responseObject);
        }
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [tips hideAnimated:YES];
            if (failBlock) {
                failBlock(@{@"errorMsg":@"网络异常",@"sate":@"---"});
                if (showTips) {
                    [QMUITips showError:@"网络异常" inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:1.8];
                }
            }
        NSLog(@"请求失败_%@_%@",task,error);
    }];

}
//body
+ (void)postWithUrl:(NSString *)url body:(NSData *)body success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failure{
  

    
    NSString *UrlStr = [NSString stringWithFormat:@"%@%@",HOST_URL,url];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:UrlStr parameters:nil error:nil];
    
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        // 设置body
        [request setHTTPBody:body];
        
        AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"text/json",
                                                     @"text/javascript",
                                                     @"text/plain",
                                                     nil];
        manager.responseSerializer = responseSerializer;
        
        [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            NSData *data = responseObject;
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (!error) {
                success(dictionary);
            } else {
                failure(error);
            }
        }] resume];
}
+ (void)postWithRequestUrl:(NSString *)requestHead AndParameters:(NSDictionary *)param FormateDict:(NSDictionary *)formatDict AndRequestBlock:(void (^)(NSDictionary *respondDic))block FailBlock:(void (^)(NSDictionary *failDict))failBlock{
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];

        NSString *UrlStr;
        if ([requestHead hasPrefix:@"http"]) {
            UrlStr = [requestHead copy];
        }else{
            UrlStr = [NSString stringWithFormat:@"%@%@",HOST_URL,requestHead];
        }
        [manager POST:UrlStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (NSString *key in formatDict) {
                if ([formatDict[key] isKindOfClass:[NSData class]]) {
                    [formData appendPartWithFormData:formatDict[key] name:key];
                }else if ([formatDict[key]isKindOfClass:[NSString class]]){
                    NSData  *data1 = [formatDict[key] dataUsingEncoding:NSUTF8StringEncoding];
                    [formData appendPartWithFormData:data1 name:key];
                }
            }

        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                  NSLog(@"返回参数%@",dictionary);

                block(dictionary);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failBlock(@{@"errorMsg":@"404"});
            NSLog(@"请求失败_%@_%@",task,error);
        }];
    }
}
+ (void)PutWithRequestUrl:(NSString *)requestHead AndParameters:(NSDictionary *)param AndRequestBlock:(void (^)(NSDictionary *))block FailBlock:(void (^)(NSDictionary *))failBlock{
    
    //    [netManager reachNetwork];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *UrlStr;
    if ([requestHead hasPrefix:@"http"]) {
        UrlStr = requestHead;
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        UrlStr = [NSString stringWithFormat:@"%@%@",HOST_URL,requestHead];
    }
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];

    NSLog(@"请求头%@ \n 参数%@",UrlStr,param);
    [manager PUT:UrlStr parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"返回参数%@",responseObject);
        if ([requestHead hasPrefix:@"http"]) {
            block(responseObject);
        }
        if ([[responseObject objectForKey:@"status"] integerValue]==1) {
            block(responseObject);
        }else{
            failBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(@{@"errorMsg":@"网络异常"});
        NSLog(@"请求失败_%@_%@",task,error);
    }];
    
}
+ (void)reachNetwork{
    //创建网络监听管理者对象
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    /*
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,//未识别的网络
     AFNetworkReachabilityStatusNotReachable     = 0,//不可达的网络(未连接)
     AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
     AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络
     };
     */
    //设置监听
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未识别的网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                
                    NSLog(@"不可达的网络(未连接)");
                [self showReachabilityStatusNotReachable];
                isDisToConnected = YES;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"2G,3G,4G...的网络");
                if (isDisToConnected) {
                    NWblock();
                    isDisToConnected = NO;
                }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"wifi的网络");
                if (isDisToConnected) {
                    NWblock();
                    isDisToConnected = NO;
                }
                break;
            default:
                break;
        }
        if (status != AFNetworkReachabilityStatusNotReachable) {
            
            
        }
    }];
    //开始监听
    [manager startMonitoring];
}
+ (void)showReachabilityStatusNotReachable{
    
}
+ (void)reachNetwork:(void (^)(void))reachableBlock{
    if (reachableBlock) {
        NWblock = reachableBlock;
    }
    [self reachNetwork];
}
//+ (NSString *)getLoacHost{
//      NSString *url = [[NSUserDefaults standardUserDefaults]objectForKey:@"cert_ip"];
//     url = @"192.168.200.129:8080/";
//    if (url.length<4) {
//        return @"";
//    }
//    if ([url hasPrefix:@"http://"]) {
//        
//    }else{
//        url = [NSString stringWithFormat:@"http://%@",url];
//    }
//   
//    return url;
//}
+(void)postWithRequestUrl:(NSString *)requestHead AndParameters:(NSDictionary *)param AndRequestBlock:(void(^)(NSDictionary *responseObject))block FailBlock:(void(^)(NSDictionary *errDic))failBlock{
    [self postWithRequestUrl:requestHead AndParameters:param AndRequestBlock:block FailBlock:failBlock ShowTips:YES];
}
@end
